<template>
  <div class="service-config-selector">
    <el-select
      v-model="selectedId"
      :placeholder="placeholder"
      :clearable="clearable"
      :filterable="filterable"
      :loading="loading"
      :disabled="disabled"
      :size="size"
      :style="{ width }"
      popper-class="batch-dialog-select-popper"
      :teleported="true"
      @change="handleChange"
      @visible-change="handleVisibleChange"
    >
      <el-option
        v-for="config in configs"
        :key="config.id"
        :label="getOptionLabel(config)"
        :value="config.id"
      >
        <div class="option-content">
          <div class="option-main">
            <el-tag :type="getServiceTypeTag(config.service_type)" size="small" class="service-tag">
              {{ getServiceTypeText(config.service_type) }}
            </el-tag>
            <span class="config-name">{{ config.config_name }}</span>
          </div>
          <div class="option-meta">
            <span class="host-port">{{ config.host }}:{{ config.port }}</span>
          </div>
        </div>
      </el-option>
    </el-select>
  </div>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import api from '@/utils/api'
import { createLogger } from '@/utils/logger'

const componentLogger = createLogger('ServiceConfigSelector')

const props = defineProps({
  modelValue: {
    type: Number,
    default: null
  },
  serviceType: {
    type: String,
    required: true,
    validator: (value) => ['kafka', 'starrocks'].includes(value)
  },
  clearable: {
    type: Boolean,
    default: true
  },
  filterable: {
    type: Boolean,
    default: true
  },
  placeholder: {
    type: String,
    default: '请选择集群'
  },
  disabled: {
    type: Boolean,
    default: false
  },
  size: {
    type: String,
    default: 'default'
  },
  width: {
    type: String,
    default: '100%'
  }
})

const emit = defineEmits(['update:modelValue', 'change'])

const loading = ref(false)
const configs = ref([])
const selectedId = ref(props.modelValue)

watch(
  () => props.modelValue,
  (newVal) => {
    selectedId.value = newVal
  },
  { immediate: true }
)

const fetchConfigs = async () => {
  try {
    loading.value = true
    const response = await api.get('/reports/service-configs', {
      params: {
        service_type: props.serviceType
      }
    })
    if (response.data.success) {
      configs.value = response.data.data || []
      componentLogger.info('集群列表加载成功', { count: configs.value.length, type: props.serviceType })
    } else {
      ElMessage.error(response.data.message || '获取集群列表失败')
    }
  } catch (error) {
    componentLogger.error('获取集群列表失败', error)
    ElMessage.error('获取集群列表失败')
  } finally {
    loading.value = false
  }
}

const handleChange = (value) => {
  emit('update:modelValue', value)
  emit('change', value)
  componentLogger.info('集群选择变化', { value })
}

const handleVisibleChange = (visible) => {
  if (visible && configs.value.length === 0) {
    fetchConfigs()
  }
}

const getOptionLabel = (config) => `${config.config_name}`

const getServiceTypeTag = (serviceType) => ({
  kafka: 'warning',
  starrocks: 'success'
}[serviceType] || '')

const getServiceTypeText = (serviceType) => ({
  kafka: 'Kafka',
  starrocks: 'StarRocks'
}[serviceType] || serviceType)

onMounted(() => {
  fetchConfigs()
})
</script>

<style scoped>
.service-config-selector {
  width: 100%;
}

.option-content {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.option-main {
  display: flex;
  align-items: center;
}

.service-tag {
  margin-right: 8px;
}

.config-name {
  font-weight: 500;
  color: #303133;
}

.option-meta {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 12px;
  color: #909399;
  margin-left: 60px;
}

.host-port {
  color: #606266;
}
</style>
